import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Modal,
  Image,
  TouchableWithoutFeedback,
  Alert,
  Dimensions,
  ActivityIndicator,
  ScrollView,
} from "react-native";
import React, { useState, useRef, useContext } from "react";
import { useSelector } from "react-redux";
import * as ImagePicker from "expo-image-picker";
// import ImageViewer from "react-native-image-zoom-viewer";
// import VideoPlayer from "expo-video-player";
import { Audio } from "expo-av";
import * as DocumentPicker from "expo-document-picker";
import * as Location from "expo-location";
// import { ResizeMode } from "expo-av";
// import { Feather } from "@expo/vector-icons";
// import { MaterialIcons } from "@expo/vector-icons";
import { Ionicons } from "@expo/vector-icons";
import { AntDesign } from "@expo/vector-icons";
// import { Foundation } from "@expo/vector-icons";
import { Madoka, Akira } from "react-native-textinput-effects";
import SelectCity from "../../components/InterView/SelectCity";
import LoadingBar from "../../components/InterView/LoadingBar";
import InterviewContext from "../../context/interview/InterviewContext";
// import AudioListItem from "../../components/InterView/AudioListItem";
import { play, pause, resume, playNext } from "../../utils/audioController";

const { width: DEVICE_WIDTH, height: DEVICE_HEIGHT } = Dimensions.get("window");

const Loading = () => {
  return (
    <View>
      <ActivityIndicator animating={true} size={"large"} />
    </View>
  );
};

const InterviewAdd = ({ route, navigation }) => {
  const intertype = route.params.type;
  const user_id = useSelector((state) => state.authR.user._id);
  const { addInterview } = useContext(InterviewContext);
  const interviewType = [
    "市级访谈",
    "县级访谈",
    "对接会讲话",
    "镇级访谈",
    "村级访谈",
    "安置点访谈",
  ];
  //加载可见性
  const [isConfirm, setIsConfirm] = useState(false);
  //拍照/打开相册可见性
  const [isVisible, setIsVisible] = useState(false);
  //摄像/打开相册可见性
  const [isVideoVisible, setIsVideoVisible] = useState(false);
  //访谈类型
  const [typeSelected, setTypeSelected] = useState(
    interviewType.indexOf(intertype)
  );
  //位置信息/座谈访谈人次信息可见性
  const [itemsVisible, setItemsVisible] = useState([true, true]);
  //添加访谈图片
  const [imageList, setImageList] = useState([]);
  //放大图片
  const [magnifypVisible, setMagnifypVisible] = useState(false);
  const [index, setIndex] = useState(0);
  const [imagesUrl, setimagesUrl] = useState([]);
  //音频
  const [audioList, setAudioList] = useState([]);
  const [currentAudio, setCurrentAudio] = useState({});
  const [currentAudioIndex, setCurrentAudioIndex] = useState(null);
  const [soundObj, setSoundObj] = useState(null);
  const [playbackObj, setPlaybackObj] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  //视频
  const refVideo = useRef(null);
  const [videoList, setvideoList] = useState([]); //存放视频url的数组
  const [inFullscreen, setInFullsreen] = useState(false);
  //定位
  const [location, setLocation] = useState(null);
  //需上传的数据
  const [fileName, setFileName] = useState("");
  const [type, setType] = useState(intertype);
  const [provincekey, setProvincekey] = useState("");
  const [citykey, setCitykey] = useState("");
  const [areakey, setAreakey] = useState("");
  const [province, setProvince] = useState("");
  const [city, setCity] = useState("");
  const [area, setArea] = useState("");
  const [address, setAddress] = useState("");
  const [latitude, setLatitude] = useState();
  const [longitude, setLongitude] = useState();
  const [municipalLeaders, setMunicipalLeaders] = useState("0");
  const [municipalDepartment, setMunicipalDepartment] = useState("0");
  const [countyLeaders, setCountyLeaders] = useState("0");
  const [countyDepartment, setCountyDepartment] = useState("0");
  const [townshipLeaders, setTownshipLeaders] = useState("0");
  const [villageCadres, setVillageCadres] = useState("0");
  const [villageDoctorsAndPrincipals, setVillageDoctorsAndPrincipals] =
    useState("0");
  const [firstSecretary, setFirstSecretary] = useState("0");
  const [NPCdeputies, setNPCdeputies] = useState("0");
  // publisher: "李艳婷"---------------------------通过AsyncStorage拿到登录者相关信息
  // latitude、longitude---------------------------暂时还没实现
  const scrollRef = useRef(null);

  // useEffect(() => {
  //   let isMounted = true;
  //   if (isMounted) {
  //     getCurrentLocation();
  //   }
  //   return () => {
  //     isMounted = false;
  //   };
  // }, []);

  //控制卡片展开/合起
  const cardVisible = (index) => {
    const itemsNewVisible = [...itemsVisible];
    itemsNewVisible[index] = !itemsNewVisible[index];
    setItemsVisible(itemsNewVisible);
  };

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      // aspect: [1, 1],
      quality: 1,
    });
    if (!result.cancelled) {
      setImageList([...imageList, result.uri]);
      setIsVisible(false);
    }
  };

  const openCamera = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
    if (permissionResult.granted === false) {
      alert("您拒绝该应用使用您的相机");
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      quality: 1,
      // aspect: [4, 3],
    });
    if (!result.cancelled) {
      setImageList([...imageList, result.uri]);
      setIsVisible(false);
    }
  };

  //  Unlike saveImageToPhone(), This method doesn't return created asset. On iOS 11+, it's possible to use this method without asking for CAMERA_ROLL permission.
  // const saveImage = async (url) => {
  //   // if (url.substring(0, 7) != "file://") {
  //   //   const localpicture = await FileSystem.downloadAsync(
  //   //     url,
  //   //     FileSystem.documentDirectory + "image.jpg"
  //   //   );
  //   //   if (localpicture.status != 200) {
  //   //     alert("下载失败！");
  //   //   } else {
  //   //     url = localpicture.uri;
  //   //   }
  //   // }
  //   setIsConfirm(true);
  //   if (hasMediaLibraryPermission) {
  //     try {
  //       MediaLibrary.saveToLibraryAsync(url).then(() => {
  //         setIsConfirm(false);
  //         alert("已保存到系统相册");
  //       });
  //     } catch (error) {
  //       setIsConfirm(false);
  //       alert("保存时出错了！");
  //     }
  //   } else {
  //     setIsConfirm(false);
  //     alert("未授权访问媒体库的权限，请在设置中进行修改");
  //   }
  // };

  // const saveImageToPhone = async (item) => {
  //   const { status } = await MediaLibrary.requestPermissionsAsync();
  //   if (status == "granted") {
  //     try {
  //       const asset = await MediaLibrary.createAssetAsync(item);
  //       MediaLibrary.createAlbumAsync("Images", asset, false)
  //         .then(() => {
  //           alert("已保存到系统相册");
  //         })
  //         .catch(() => {
  //           alert("保存时出错了！");
  //         });
  //     } catch (error) {
  //       alert("保存时出错了！");
  //     }
  //   } else {
  //     alert("未授权访问媒体库的权限，请在设置中进行修改");
  //   }
  // };

  const deleteImage = (url) => {
    Alert.alert("提示", "要删除这张照片吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let images = imageList.filter((item) => item !== url);
          setImageList(images);
        },
      },
    ]);
  };

  const pickVideo = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Videos,
      allowsEditing: true,
      quality: 1,
    });
    if (!result.cancelled) {
      setvideoList([...videoList, result.uri]);
      setIsVideoVisible(false);
    }
  };

  const openVideoCamera = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
    if (permissionResult.granted === false) {
      alert("您拒绝该应用使用您的相机");
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Videos,
      allowsEditing: true,
      quality: 1,
      // aspect: [4, 3],
    });
    if (!result.cancelled) {
      setvideoList([...videoList, result.uri]);
      setIsVideoVisible(false);
    }
  };

  // const saveVideo = async (url) => {
  //   if (url.substring(0, 7) != "file://") {
  //     const localvideo = await FileSystem.downloadAsync(
  //       url,
  //       FileSystem.documentDirectory + "video.mp4"
  //     );
  //     if (localvideo.status != 200) {
  //       alert("下载失败！");
  //     } else {
  //       url = localvideo.uri;
  //     }
  //   }
  //   if (hasMediaLibraryPermission) {
  //     try {
  //       MediaLibrary.saveToLibraryAsync(url).then(() => {
  //         alert("已保存到系统相册");
  //       });
  //     } catch (error) {
  //       alert("保存时出错了！");
  //     }
  //   } else {
  //     alert("未授权访问媒体库的权限，请在设置中进行修改");
  //   }
  // };

  // const saveVideoAlert = (url) => {
  //   Alert.alert("提示", "要保存这个视频吗?", [
  //     {
  //       text: "取消",
  //       onPress: () => console.log("Cancel Pressed"),
  //       style: "cancel",
  //     },
  //     {
  //       text: "确定",
  //       onPress: () => {
  //         saveVideo(url);
  //       },
  //     },
  //   ]);
  // };

  const deleteVideo = (url) => {
    Alert.alert("提示", "要删除这个视频吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let videos = videoList.filter((item) => item !== url);
          setvideoList(videos);
        },
      },
    ]);
  };

  const pickAudio = async () => {
    let result = await DocumentPicker.getDocumentAsync({});
    if (result.type != "cancel") {
      if (result.mimeType.substring(0, 5) != "audio") {
        alert("请选择音频文件");
      } else {
        setAudioList([...audioList, { uri: result.uri, name: result.name }]);
      }
    }
  };

  const deleteAudio = (audio) => {
    Alert.alert("提示", "要删除这个录音吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          setAudioList((audioList) =>
            audioList.filter((item) => item.uri != audio.uri)
          );
        },
      },
    ]);
  };

  //处理录音点击事件
  const handleAudioPress = async (audio) => {
    const index = audioList.indexOf(audio);
    // playing audio for the first time.
    if (soundObj === null) {
      const playbackObj = new Audio.Sound();
      const status = await play(playbackObj, audio.uri);
      setCurrentAudio(audio);
      setCurrentAudioIndex(index);
      setIsPlaying(true);
      setPlaybackObj(playbackObj);
      setSoundObj(status);

      playbackObj.setOnPlaybackStatusUpdate((playbackStatus) => {
        if (playbackStatus.didJustFinish) {
          setCurrentAudio({});
          setCurrentAudioIndex(null);
          setIsPlaying(false);
          setPlaybackObj(null);
          setSoundObj(null);
        }
      });
    } else {
      // pause audio
      if (
        soundObj.isLoaded &&
        soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await pause(playbackObj);
        setSoundObj(status);
        setIsPlaying(false);
      }
      // resume audio
      if (
        soundObj.isLoaded &&
        !soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await resume(playbackObj);
        setSoundObj(status);
        setIsPlaying(true);
      }
      // select another audio
      if (soundObj.isLoaded && index !== currentAudioIndex) {
        const status = await playNext(playbackObj, audio.uri);
        setCurrentAudio(audio);
        setSoundObj(status);
        setIsPlaying(true);
        setCurrentAudioIndex(index);
      }
    }
  };

  const getCurrentDate = () => {
    let newDate = new Date();
    let year = newDate.getFullYear();
    let month = newDate.getMonth() + 1;
    let date = newDate.getDate();
    return year + "/" + month + "/" + date;
  };

  const getCurrentTime = () => {
    let newDate = new Date();
    let currentTime = newDate.toLocaleTimeString();
    return currentTime;
  };

  const getCurrentLocation = async () => {
    let { status } = await Location.requestForegroundPermissionsAsync();
    if (status == "granted") {
      console.log("--------------------------------", status);
      let location = await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.Highest,
      });
      console.log("+++++++++++++++++++++++++++++++");
      console.log(location);
      setLatitude(location.coords.latitude);
      setLongitude(location.coords.longitude);
    }
  };

  const handleProvince = (key, province) => {
    setProvincekey(key);
    setProvince(province);
  };

  const handleCity = (key, city) => {
    setCitykey(key);
    setCity(city);
  };

  const handleArea = (key, area) => {
    setAreakey(key);
    setArea(area);
  };

  const handleAddress = (address) => {
    setAddress(address);
  };

  const confirmAdd = () => {
    Alert.alert("提示", "确定要提交吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          if (fileName == "") {
            Alert.alert("提示", "文件名不能为空", [{ text: "确定" }]);
            return;
          }
          if (
            Object.is(Number(municipalLeaders), NaN) ||
            Object.is(Number(municipalDepartment), NaN) ||
            Object.is(Number(countyLeaders), NaN) ||
            Object.is(Number(countyDepartment), NaN) ||
            Object.is(Number(townshipLeaders), NaN) ||
            Object.is(Number(villageCadres), NaN) ||
            Object.is(Number(villageDoctorsAndPrincipals), NaN) ||
            Object.is(Number(firstSecretary), NaN) ||
            Object.is(Number(NPCdeputies), NaN)
          ) {
            Alert.alert("提示", "座谈访谈人次应输入数字", [{ text: "确定" }]);
            return;
          }
          setIsConfirm(true);
          let addData = {
            fileName: fileName,
            type: type,
            provincekey: provincekey,
            province: province,
            citykey: citykey,
            city: city,
            areakey: areakey,
            area: area,
            address: address,
            latitude: "",
            longitude: "",
            municipalLeaders: Number(municipalLeaders),
            municipalDepartment: Number(municipalDepartment),
            countyLeaders: Number(countyLeaders),
            countyDepartment: Number(countyDepartment),
            townshipLeaders: Number(townshipLeaders),
            villageCadres: Number(villageCadres),
            villageDoctorsAndPrincipals: Number(villageDoctorsAndPrincipals),
            firstSecretary: Number(firstSecretary),
            NPCdeputies: Number(NPCdeputies),
            interviewImageList: imageList,
            interviewAudioList: audioList,
            interviewVideoList: videoList,
            date: getCurrentDate(),
            time: getCurrentTime(),
            publisher: user_id,
          };
          addInterview(
            addData,
            () => {
              navigation.goBack();
            },
            () => {
              setIsConfirm(false);
            }
          );
        },
      },
    ]);
  };

  return (
    <View style={styles.page}>
      <LoadingBar visible={isConfirm} />
      <ScrollView showsVerticalScrollIndicator={false} ref={scrollRef}>
        {/* 访谈文件名 */}
        <View style={styles.section}>
          <View style={[styles.tagItem, { marginBottom: 8 }]}>
            <Text style={styles.tagtitle}>访谈文件名</Text>
          </View>
          <Akira
            label={"请输入访谈文件名"}
            borderColor={"#FCEDD9"}
            inputPadding={13}
            labelStyle={{
              color: "#A80108",
              fontSize: 16,
            }}
            value={fileName}
            onChangeText={(text) => setFileName(text)}
            style={{
              marginBottom: 10,
              marginHorizontal: 5,
            }}
          />
        </View>

        {/* 访谈类型 */}
        <View style={styles.section}>
          <View style={styles.tagItem}>
            <Text style={styles.tagtitle}>访谈类型</Text>
          </View>
          <View style={styles.interviewtype}>
            {interviewType.map((tag, index) => {
              return (
                <TouchableOpacity
                  key={index}
                  onPress={() => {
                    setTypeSelected(index);
                    setType(interviewType[index]);
                  }}
                >
                  <View
                    style={
                      index === typeSelected
                        ? styles.selecttagborder
                        : styles.tagborder
                    }
                  >
                    <Text
                      style={
                        index === typeSelected ? styles.selectedTag : styles.tag
                      }
                    >
                      {tag}
                    </Text>
                  </View>
                </TouchableOpacity>
              );
            })}
          </View>
        </View>

        {/* 位置信息 */}
        {itemsVisible[0] ? (
          <View style={styles.addModal}>
            <TouchableOpacity
              onPress={() => {
                cardVisible(0);
              }}
            >
              <View style={styles.heqititle}>
                <View style={styles.titleleft}></View>
                <Text style={styles.heqiBiaoTi}>位置信息</Text>
              </View>
            </TouchableOpacity>
          </View>
        ) : (
          <View style={styles.addModal}>
            <TouchableOpacity
              onPress={() => {
                cardVisible(0);
              }}
            >
              <View style={styles.titleView}>
                <AntDesign
                  name="enviromento"
                  size={24}
                  color="#475565"
                  style={{ marginRight: 10 }}
                />
                <Text style={styles.zhankaititle}>位置信息</Text>
              </View>
            </TouchableOpacity>

            <SelectCity
              style={{ marginTop: "20" }}
              provincekey={provincekey}
              citykey={citykey}
              areakey={areakey}
              address={address}
              handleProvince={(provincekey, province) => {
                handleProvince(provincekey, province);
              }}
              handleCity={(citykey, city) => {
                handleCity(citykey, city);
              }}
              handleArea={(areakey, area) => {
                handleArea(areakey, area);
              }}
              handleAddress={(address) => {
                handleAddress(address);
              }}
            />

            <View
              style={{
                flexDirection: "row-reverse",
                marginLeft: 10,
              }}
            >
              <TouchableOpacity
                onPress={() => {
                  cardVisible(0);
                }}
              >
                <Text style={{ color: "#5e5e5e", fontSize: 16 }}>完成</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}

        {/* 座谈访谈人次 */}
        {itemsVisible[1] ? (
          <View style={styles.addModal}>
            <TouchableOpacity
              onPress={() => {
                //展开卡片
                cardVisible(1);
              }}
            >
              <View style={styles.heqititle}>
                <View style={styles.titleleft}></View>
                <Text style={styles.heqiBiaoTi}>座谈访谈人次</Text>
              </View>
            </TouchableOpacity>
          </View>
        ) : (
          <View style={styles.addModal}>
            <TouchableOpacity
              onPress={() => {
                cardVisible(1);
              }}
            >
              <View style={styles.titleView}>
                <Ionicons
                  name="people-outline"
                  size={25}
                  color="#475565"
                  style={{ marginRight: 10 }}
                />
                <Text style={styles.zhankaititle}>座谈访谈人次</Text>
              </View>
            </TouchableOpacity>

            <View style={{ paddingVertical: 15, paddingHorizontal: 8 }}>
              <Madoka
                style={styles.input}
                label={"市级领导"}
                borderColor={"#aee2c9"}
                labelStyle={{ color: "#008445" }}
                inputStyle={{ color: "#f4a197" }}
                value={municipalLeaders}
                onChangeText={(text) => {
                  setMunicipalLeaders(text);
                }}
                keyboardType="numeric"
              />
              <Madoka
                style={styles.input}
                label={"市级行业部门"}
                borderColor={"#aee2c9"}
                labelStyle={{ color: "#008445" }}
                inputStyle={{ color: "#f4a197" }}
                value={municipalDepartment}
                onChangeText={(text) => {
                  setMunicipalDepartment(text);
                }}
                keyboardType="numeric"
              />
              <Madoka
                style={styles.input}
                label={"县级领导"}
                borderColor={"#aee2c9"}
                labelStyle={{ color: "#008445" }}
                inputStyle={{ color: "#f4a197" }}
                value={countyLeaders}
                onChangeText={(text) => {
                  setCountyLeaders(text);
                }}
                keyboardType="numeric"
              />
              <Madoka
                style={styles.input}
                label={"县级行业部门"}
                borderColor={"#aee2c9"}
                labelStyle={{ color: "#008445" }}
                inputStyle={{ color: "#f4a197" }}
                value={countyDepartment}
                onChangeText={(text) => {
                  setCountyDepartment(text);
                }}
                keyboardType="numeric"
              />
              <Madoka
                style={styles.input}
                label={"乡镇干部"}
                borderColor={"#aee2c9"}
                labelStyle={{ color: "#008445" }}
                inputStyle={{ color: "#f4a197" }}
                value={townshipLeaders}
                onChangeText={(text) => {
                  setTownshipLeaders(text);
                }}
                keyboardType="numeric"
              />
              <Madoka
                style={styles.input}
                label={"村干部"}
                borderColor={"#aee2c9"}
                labelStyle={{ color: "#008445" }}
                inputStyle={{ color: "#f4a197" }}
                value={villageCadres}
                onChangeText={(text) => {
                  setVillageCadres(text);
                }}
                keyboardType="numeric"
              />
              <Madoka
                style={styles.input}
                label={"村医、小学校长"}
                borderColor={"#aee2c9"}
                labelStyle={{ color: "#008445" }}
                inputStyle={{ color: "#f4a197" }}
                value={villageDoctorsAndPrincipals}
                onChangeText={(text) => {
                  setVillageDoctorsAndPrincipals(text);
                }}
                keyboardType="numeric"
              />
              <Madoka
                style={styles.input}
                label={"第一书记或驻村工作队"}
                borderColor={"#aee2c9"}
                labelStyle={{ color: "#008445" }}
                inputStyle={{ color: "#f4a197" }}
                value={firstSecretary}
                onChangeText={(text) => {
                  setFirstSecretary(text);
                }}
                keyboardType="numeric"
              />
              <Madoka
                style={styles.input}
                label={"人大代表和政协委员"}
                borderColor={"#aee2c9"}
                labelStyle={{ color: "#008445" }}
                inputStyle={{ color: "#f29388" }}
                value={NPCdeputies}
                onChangeText={(text) => {
                  setNPCdeputies(text);
                }}
                keyboardType="numeric"
              />
            </View>

            <View
              style={{
                flexDirection: "row-reverse",
                marginLeft: 10,
              }}
            >
              <TouchableOpacity
                onPress={() => {
                  cardVisible(1);
                }}
              >
                <Text style={{ color: "#f18578", fontSize: 16 }}>完成</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}

        {/* <View style={styles.section}>
          <View style={styles.tagItem}>
            <Text style={styles.tagtitle}>访谈图片</Text>
          
            {imageList.length != 0 ? (
              <TouchableOpacity
                onPress={() => {
                  setIsVisible(true);
                }}
                style={styles.smalladdimage}
              >
                <MaterialIcons name="add-a-photo" size={20} color="#bcbcbc" />
              </TouchableOpacity>
            ) : null}
          </View>

        
          {imageList.length == 0 ? (
            <TouchableOpacity
              onPress={() => {
                setIsVisible(true);
              }}
              style={[styles.addimage, { marginLeft: 15 }]}
            >
              <MaterialIcons name="add-a-photo" size={40} color="#bcbcbc" />
            </TouchableOpacity>
          ) : null}

          
          <View style={styles.imageList}>
            {imageList.map((imageurl, index) => {
              return (
                <View key={index}>
                
                  <TouchableOpacity
                    onPress={() => {
                      deleteImage(imageurl);
                    }}
                    style={
                      index % 3 == 2
                        ? styles.lastcoldeleteimage
                        : styles.deleteimage
                    }
                  >
                    <Feather
                      name="x"
                      size={15}
                      color="#ffffff"
                      style={{ zIndex: 10 }}
                    />
                  </TouchableOpacity>
                
                  <TouchableOpacity
                    onPress={() => {
                      var newimageList = imageList.map((item) => ({
                        url: item,
                        props: {},
                      }));
                      setimagesUrl(newimageList);
                      setIndex(index);
                      setMagnifypVisible(true);
                    }}
                  >
                    <Image
                      source={{ uri: imageurl }}
                      style={[
                        index % 3 == 2
                          ? styles.lascolsingleimage
                          : styles.singleimage,
                        { resizeMode: "cover" },
                      ]}
                    />
                  </TouchableOpacity>
                </View>
              );
            })}
          </View>

        
          <Modal animationType="fade" transparent={true} visible={isVisible}>
            <View style={styles.ModalBackground}></View>

            <TouchableWithoutFeedback
              onPress={() => {
                setIsVisible(false);
              }}
            >
              <View style={styles.ModalTop}></View>
            </TouchableWithoutFeedback>

            <View style={styles.ModalStyle}>
              <TouchableOpacity
                style={styles.ModalOption}
                onPress={() => {
                  openCamera();
                }}
              >
                <Text style={styles.ModalText}>拍摄</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.ModalOption, { borderBottomWidth: 4 }]}
                onPress={() => pickImage()}
              >
                <Text style={styles.ModalText}>从相册选择</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={styles.ModalOption}
                onPress={() => {
                  setIsVisible(false);
                }}
              >
                <Text style={styles.ModalText}>取消</Text>
              </TouchableOpacity>
            </View>
          </Modal>
        </View>
        
        <Modal visible={magnifypVisible} animationType={"fade"}>
          <ImageViewer
            imageUrls={imagesUrl}
            saveToLocalByLongPress={false}
            menuContext={{ saveToLocal: "保存图片", cancel: "取消" }}
            loadingRender={Loading}
            index={index}
            onClick={() => {
              setMagnifypVisible(false);
            }}
            // onSave={() => {
            //   saveImage(imagesUrl[index].url);
            // }}
          />
        </Modal>
      
        <View style={styles.section}>
          <View style={styles.tagItem}>
            <Text style={styles.tagtitle}>访谈录音</Text>
      
            {audioList.length != 0 ? (
              <TouchableOpacity
                onPress={() => {
                  pickAudio();
                }}
                style={[styles.smalladdimage]}
              >
                <Foundation name="record" size={20} color="#bcbcbc" />
              </TouchableOpacity>
            ) : null}
          </View>
          
          {audioList.length == 0 ? (
            <TouchableOpacity
              onPress={() => {
                pickAudio();
              }}
              style={[styles.addimage, { marginLeft: 15 }]}
            >
              <Foundation name="record" size={45} color="#bcbcbc" />
            </TouchableOpacity>
          ) : null}

          <View style={styles.audiolistStyle}>
            {audioList.map((item, index) => {
              return (
                <AudioListItem
                  key={index}
                  audioName={item.name}
                  isPlaying={isPlaying}
                  activeListItem={currentAudioIndex === index}
                  onAudioPress={() => handleAudioPress(item)}
                  deleteAudio={() => deleteAudio(item)}
                />
              );
            })}
          </View>
        </View>
      
        <View style={styles.section}>
          <View style={styles.tagItem}>
            <Text style={styles.tagtitle}>访谈视频</Text>
            
            {videoList.length != 0 ? (
              <TouchableOpacity
                onPress={() => {
                  setIsVideoVisible(true);
                }}
                style={[styles.smalladdimage]}
              >
                <MaterialIcons
                  name="video-collection"
                  size={20}
                  color="#bcbcbc"
                />
              </TouchableOpacity>
            ) : null}
          </View>

        
          {videoList.length == 0 ? (
            <TouchableOpacity
              onPress={() => {
                setIsVideoVisible(true);
              }}
              style={[styles.addimage, { marginLeft: 15 }]}
            >
              <MaterialIcons
                name="video-collection"
                size={40}
                color="#bcbcbc"
              />
            </TouchableOpacity>
          ) : null}

          <View style={styles.videoList}>
            {videoList.map((videourl, index) => {
              return (
                <View key={index}>
            
                  <TouchableOpacity
                    onPress={() => {
                      deleteVideo(videourl);
                    }}
                    style={styles.deletevideo}
                  >
                    <Feather
                      name="x"
                      size={19}
                      color="#ffffff"
                      style={{ zIndex: 10 }}
                    />
                  </TouchableOpacity>

                  <View style={{ marginBottom: 10 }}>
                    <VideoPlayer
                      videoProps={{
                        shouldPlay: false,
                        resizeMode: ResizeMode.CONTAIN,
                        source: {
                          uri: videourl,
                        },
                        ref: refVideo,
                      }}
                      // fullscreen={{
                      //   inFullscreen: inFullscreen,
                      //   enterFullscreen: async () => {
                      //     setStatusBarHidden(true, "fade");
                      //     setInFullsreen(!inFullscreen);
                      //     await ScreenOrientation.lockAsync(
                      //       ScreenOrientation.OrientationLock.LANDSCAPE_LEFT
                      //     );
                      //     refVideo.current.playAsync();
                      //   },
                      //   exitFullscreen: async () => {
                      //     setStatusBarHidden(false, "fade");
                      //     setInFullsreen(!inFullscreen);
                      //     await ScreenOrientation.lockAsync(
                      //       ScreenOrientation.OrientationLock.PORTRAIT
                      //     );
                      //     refVideo.current.pauseAsync();
                      //   },
                      // }}
                      style={{
                        height: inFullscreen
                          ? DEVICE_WIDTH
                          : (DEVICE_WIDTH * 3) / 5,
                        width: inFullscreen
                          ? DEVICE_HEIGHT
                          : (DEVICE_WIDTH * 4) / 5,
                        videoBackgroundColor: "#000000",
                      }}
                    />
                  </View>
                </View>
              );
            })}

            
            <Modal
              animationType="fade"
              transparent={true}
              visible={isVideoVisible}
            >
              <View style={styles.ModalBackground}></View>

              <TouchableWithoutFeedback
                onPress={() => {
                  setIsVideoVisible(false);
                }}
              >
                <View style={styles.ModalTop}></View>
              </TouchableWithoutFeedback>

              <View style={styles.ModalStyle}>
                <TouchableOpacity
                  style={styles.ModalOption}
                  onPress={() => {
                    openVideoCamera();
                  }}
                >
                  <Text style={styles.ModalText}>摄像</Text>
                </TouchableOpacity>

                <TouchableOpacity
                  style={[styles.ModalOption, { borderBottomWidth: 4 }]}
                  onPress={() => pickVideo()}
                >
                  <Text style={styles.ModalText}>从相册选择</Text>
                </TouchableOpacity>

                <TouchableOpacity
                  style={styles.ModalOption}
                  onPress={() => {
                    setIsVideoVisible(false);
                  }}
                >
                  <Text style={styles.ModalText}>取消</Text>
                </TouchableOpacity>
              </View>
            </Modal>
          </View>
        </View> */}

        {/* 提交按钮 */}
        <TouchableOpacity
          style={[styles.button]}
          onPress={() => {
            confirmAdd();
          }}
        >
          <Text style={styles.buttonText}>提交</Text>
        </TouchableOpacity>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  page: {
    backgroundColor: "#ffffff",
    height: DEVICE_HEIGHT,
    paddingTop: 15,
    paddingBottom: 70,
  },
  section: {
    marginLeft: 20,
    marginBottom: 20,
    marginRight: 20,
  },
  tagItem: {
    borderBottomWidth: 1,
    borderBottomColor: "#cccccc",
    paddingBottom: 5,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 15,
  },
  tagtitle: {
    fontSize: 18,
    marginLeft: 10,
    fontWeight: "bold",
  },
  interviewtype: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignContent: "center",
    flexWrap: "wrap",
    marginHorizontal: 5,
    marginBottom: 5,
  },
  tagborder: {
    width: DEVICE_WIDTH / 4,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    borderWidth: 1,
    borderColor: "#d1d1d6",
    borderRadius: 2,
    marginBottom: 10,
  },
  selecttagborder: {
    width: DEVICE_WIDTH / 4,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    borderWidth: 1,
    borderColor: "#F9be7d",
    borderRadius: 2,
    marginBottom: 10,
  },
  tag: {
    color: "#d1d1d6",
    fontSize: 14,
    includeFontPadding: false,
    textAlignVertical: "center",
    paddingBottom: 4,
    paddingTop: 4,
  },
  selectedTag: {
    color: "#F9be7d",
    fontSize: 14,
    includeFontPadding: false,
    textAlignVertical: "center",
    paddingBottom: 4,
    paddingTop: 4,
  },
  addModal: {
    justifyContent: "flex-start",
    marginHorizontal: 25,
    marginBottom: 35,
    flexDirection: "column",
    padding: 18,
    backgroundColor: "#fff",
    borderRadius: 20,
    elevation: 7, //设置阴影角度，通过这个设置有无阴影
    shadowRadius: 3, // 设置阴影模糊半径
    shadowOpacity: 0.1, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 0,
    },
  },
  addressStyle: {
    height: 55,
    borderColor: "gray",
    borderWidth: 0.5,
    borderRadius: 8,
    paddingHorizontal: 8,
  },
  //卡片合起title位置
  heqititle: {
    flexDirection: "row",
    justifyContent: "flex-start",
    alignItems: "center",
  },
  // 卡片合起最左装饰
  titleleft: {
    height: 30,
    width: 3,
    marginTop: 1,
    backgroundColor: "#fbd6ae",
    marginRight: 10,
  },
  heqiBiaoTi: {
    textAlign: "center",
    color: "#000000",
    fontWeight: "bold",
    opacity: 0.7,
    fontSize: 18,
  },
  // 卡片展开标题位置样式
  titleView: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    marginTop: 15,
  },
  // 卡片展开标题文字样式
  zhankaititle: {
    textAlign: "center",
    color: "#404d5b",
    fontWeight: "bold",
    opacity: 0.8,
    fontSize: 22,
  },
  //访谈图片位置信息
  imageList: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "flex-start",
    alignContent: "center",
    paddingHorizontal: ((DEVICE_WIDTH * 3) / 20 - 40) / 2,
  },
  videoList: {
    flexDirection: "column",
    justifyContent: "flex-start",
    alignItems: "center",
  },
  //删除图标的位置信息
  deleteimage: {
    position: "absolute",
    zIndex: 5,
    right: DEVICE_WIDTH / 20,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  //最后一列删除图标的位置信息
  lastcoldeleteimage: {
    position: "absolute",
    zIndex: 5,
    right: 0,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  deletevideo: {
    position: "absolute",
    zIndex: 5,
    right: 0,
    top: 0,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  downloadvideo: {
    position: "absolute",
    zIndex: 5,
    left: 0,
    top: 0,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  addimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    backgroundColor: "#efefef",

    marginBottom: DEVICE_WIDTH / 20,
    alignItems: "center",
    justifyContent: "center",
  },
  smalladdimage: {
    width: DEVICE_WIDTH / 11,
    height: DEVICE_WIDTH / 11,
    backgroundColor: "#efefef",

    marginRight: 2,
    marginBottom: 3,
    alignItems: "center",
    justifyContent: "center",
  },
  singleimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginRight: DEVICE_WIDTH / 20,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
  },
  lascolsingleimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
  },
  // 拍照/打开相机背景样式
  ModalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  ModalTop: {
    flex: 1,
  },
  ModalStyle: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    backgroundColor: "#ffffff",
    zIndex: 1,
    position: "relative",
  },
  ModalOption: {
    width: "100%",
    padding: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: "#e6e6e6",
  },
  ModalText: {
    alignSelf: "center",
    fontSize: 16,
    color: "#201D1D",
  },
  button: {
    backgroundColor: "#A80108",
    padding: 20,
    borderRadius: 15,
    alignItems: "center",
    marginHorizontal: 38,
    marginTop: 10,
    marginBottom: 100,
  },
  buttonText: {
    fontSize: 16,
    color: "#ffffff",
    fontWeight: "600",
  },
  card: {
    paddingVertical: 15,
    paddingHorizontal: 8,
  },
  input: {
    marginTop: 4,
  },
  audiolistStyle: {
    paddingTop: 10,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
  },
});

export default InterviewAdd;
